<template>
  <div class="">
    <el-card>
      <el-form
        ref="addruleFormRef"
        style="max-width: 100%"
        :model="addruleForm"
        status-icon
        label-width="auto"
        class="demo-ruleForm"
        :rules="rules"
      >
        <el-form-item label="剧本名" prop="script_name" style="width: 400px">
          <el-input
            v-model="addruleForm.script_name"
            type="text"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item label="价格" prop="price" style="width: 400px">
          <el-input
            v-model="addruleForm.price"
            type="number"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item label="游玩时间" prop="play_time" style="width: 400px">
          <el-input
            v-model="addruleForm.play_time"
            type="text"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item label="封面图">
          <div class="el-upload" @click="openCover">
            <img
              v-if="addruleForm.cover"
              :src="URL + '/' + addruleForm.cover"
              style="width: 100px; height: 100px"
            />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </div>
        </el-form-item>

        <el-form-item label="难度" prop="difficulty_id">
          <el-select
            v-model="addruleForm.difficulty_id"
            placeholder="Select"
            size="large"
            style="width: 240px"
          >
            <el-option
              v-for="item in difficultyList"
              :key="item.id"
              :label="item.diff_name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="情景" prop="circumstancesCateId">
          <el-select
            v-model="addruleForm.circumstancesCateId"
            placeholder="Select"
            size="large"
            style="width: 240px"
          >
            <el-option
              v-for="item in circumstancesCateList"
              :key="item.id"
              :label="item.cate_name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="人数" prop="peopleNumCateId">
          <el-select
            v-model="addruleForm.peopleNumCateId"
            placeholder="Select"
            size="large"
            style="width: 240px"
          >
            <el-option
              v-for="item in peopleNumCateList"
              :key="item.id"
              :label="item.cate_name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="类型" prop="characterCateId">
          <el-select
            v-model="addruleForm.characterCateId"
            placeholder="Select"
            size="large"
            style="width: 240px"
          >
            <el-option
              v-for="item in characterCateList"
              :key="item.id"
              :label="item.cate_name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="角色">
          <div
            style="display: flex; justify-content: space-between; width: 100%"
          >
            <el-button
              type="primary"
              style="margin-bottom: 10px"
              @click="addRoleBtn"
              >添加角色</el-button
            >
          </div>

          <div v-if="roleList.length > 0">
            <div style="margin-bottom: 10px">
              <el-button type="primary" v-if="!isEdit" @click="isEdit = true"
                >编辑</el-button
              >

              <el-button type="danger" v-if="isEdit" @click="delRole"
                >删除</el-button
              >
              <el-button type="info" v-if="isEdit" @click="cancelRoleEdit"
                >取消</el-button
              >
            </div>
            <div style="display: flex; width: 100%">
              <el-card
                style="max-width: 100px; margin: 0 10px"
                v-for="card in roleList"
                :key="card.id"
                :shadow="
                  isEdit && card.id == checkedRoleId ? 'always' : 'never'
                "
                @click="checkedRole(card.id)"
              >
                <template #header>{{ card.role_name }} </template>
                <img :src="URL + '/' + card.img" style="width: 100%" />
              </el-card>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="简介" prop="content">
          <el-input
            v-model="addruleForm.content"
            style="width: 540px"
            :rows="5"
            type="textarea"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="addsubmitForm(addruleFormRef)"
            >确定</el-button
          >
          <el-button @click="$router.replace('/playmanager/playlist')"
            >取消</el-button
          >
        </el-form-item>
      </el-form>
    </el-card>
    <!-- 封面图 -->
    <el-dialog v-model="coverdialogVisible" title="封面图" width="1000">
      <el-card style="max-width: 100%">
        <div class="btn">
          <el-upload
            class="avatar-uploader"
            :action="URL + '/admin/uploadpicture'"
            :show-file-list="false"
            name="picture"
            :data="{ type: 1 }"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            multiple
          >
            <el-button type="primary" size="large">单击上传</el-button>
          </el-upload>
        </div>
        <div class="bigbox">
          <div
            class="box"
            v-for="coverPicture in coverPictures"
            :key="coverPicture.id"
            @click="checkedPicture(coverPicture)"
          >
            <img
              :src="URL + '/' + coverPicture.img"
              style="width: 80px; height: 80px"
            />
            <!-- 选中 -->
            <div
              class="overspread"
              v-if="coverPicture.id == checkedCoverInfo.id"
            >
              <el-icon><Check /></el-icon>
            </div>
          </div>
        </div>
        <el-pagination
          small
          background
          layout="prev, pager, next"
          :total="total"
          class="mt-4"
          :page-size="pageSize"
          @change="changePage"
          style="display: flex; justify-content: center"
        />
      </el-card>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelCover">Cancel</el-button>
          <el-button type="primary" @click="confirmCover"> Confirm </el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 角色图片 -->
    <el-dialog
      v-model="addrolePicturedialogVisible"
      title="角色图片"
      width="1000"
    >
      <el-card style="max-width: 100%">
        <div class="btn">
          <el-upload
            class="avatar-uploader"
            :action="URL + '/admin/uploadpicture'"
            :show-file-list="false"
            name="picture"
            :data="{ type: 2 }"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            multiple
          >
            <el-button type="primary" size="large">单击上传</el-button>
          </el-upload>
        </div>
        <div class="bigbox">
          <div
            class="box"
            v-for="rolepicture in rolePictures"
            :key="rolepicture.id"
            @click="checkedRolePicture(rolepicture)"
          >
            <img
              :src="URL + '/' + rolepicture.img"
              style="width: 80px; height: 80px"
            />
            <!-- 选中 -->
            <div
              class="overspread"
              v-if="rolepicture.id == checkedRolePictureInfo.id"
            >
              <el-icon><Check /></el-icon>
            </div>
          </div>
        </div>
        <el-pagination
          small
          background
          layout="prev, pager, next"
          :total="totalRole"
          class="mt-4"
          :page-size="pageSize"
          @change="changePageRole"
          style="display: flex; justify-content: center"
        />
      </el-card>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelRolePicture">Cancel</el-button>
          <el-button type="primary" @click="confirmRolePicture">
            Confirm
          </el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 添加角色 -->
    <el-dialog v-model="addroledialogVisible" title="Tips" width="500">
      <el-form
        ref="addroleruleFormRef"
        style="max-width: 600px"
        :model="addroleruleForm"
        status-icon
        label-width="auto"
        class="demo-ruleForm"
        :rules="addrolerules"
      >
        <el-form-item label="角色名" prop="role_name">
          <el-input
            v-model="addroleruleForm.role_name"
            type="text"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item label="角色图片">
          <div class="el-upload" @click="openRolePicture">
            <img
              v-if="addroleruleForm.img"
              :src="URL + '/' + addroleruleForm.img"
              style="width: 100px; height: 100px"
            />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </div>
        </el-form-item>
        <el-form-item label="角色详情" prop="content">
          <el-input
            v-model="addroleruleForm.content"
            style="width: 540px"
            :rows="5"
            type="textarea"
            autocomplete="off"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="addroledialogVisible = false">Cancel</el-button>
          <el-button type="primary" @click="confirmRole(addroleruleFormRef)">
            Confirm
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
const URL = import.meta.env.VITE_APP_API_URL;
import { reqCategoryList, reqGetDifficulty } from "@/api/category/index";
import { ResCategoryList, ReqGetDifficulty } from "@/api/category/model";
import { reqGgmAdd } from "@/api/ggm/index";
import { reqGetRole, reqAddRole, reqDelRole } from "@/api/ggmroles/index";
import { ReqGetRole } from "@/api/ggmroles/model";
import { reqGetPicture } from "@/api/picture/index";
import { reqGetPictureData } from "@/api/picture/model";
import { FormInstance, FormRules, UploadProps } from "element-plus";
import { useRoute, useRouter } from "vue-router";
const $router = useRouter();
const $route = useRoute();

const addruleForm = ref({
  script_name: "",
  price: "",
  play_time: "",
  cover: "",
  circumstancesCateId: "",
  peopleNumCateId: "",
  characterCateId: "",
  difficulty_id: "",
  content: "",
});

const addroleruleForm = ref({
  role_name: "",
  img: "",
  content: "",
  mmg_id: 0,
});

const page = ref<number>(1);
const pageRole = ref<number>(1);
const pageSize = ref<number>(32);
const coverType = ref<number>(1);
const roleType = ref<number>(2);
const total = ref<number>(0);
const totalRole = ref<number>(0);
const coverdialogVisible = ref<boolean>(false);
const addroledialogVisible = ref<boolean>(false);
const addrolePicturedialogVisible = ref<boolean>(false);
const difficultyList = ref<ReqGetDifficulty[]>([]);
const circumstancesCateList = ref<ResCategoryList[]>([]);
const peopleNumCateList = ref<ResCategoryList[]>([]);
const characterCateList = ref<ResCategoryList[]>([]);
const addruleFormRef = ref<FormInstance>();
const addroleruleFormRef = ref<FormInstance>();
const coverPictures = ref<reqGetPictureData[]>([]);
const rolePictures = ref<reqGetPictureData[]>([]);
const checkedCoverInfo = ref({ id: 0, img: "" });
const checkedRolePictureInfo = ref({ id: 0, img: "" });
const checkedRoleId = ref<number>(0);
const roleList = ref<ReqGetRole[]>([]);
const isEdit = ref<boolean>(false);

const rules = ref<FormRules<typeof addruleForm>>({
  script_name: [{ required: true, trigger: "blur", message: "请输入剧本名" }],
  price: [{ required: true, trigger: "blur", message: "请输入价格" }],
  play_time: [{ required: true, trigger: "blur", message: "请输入游玩时间" }],
  difficulty_id: [{ required: true, trigger: "change", message: "请选择难度" }],
  circumstancesCateId: [
    { required: true, trigger: "change", message: "请选择情景" },
  ],
  peopleNumCateId: [
    { required: true, trigger: "change", message: "请选择人数" },
  ],
  characterCateId: [
    { required: true, trigger: "change", message: "请选择类型" },
  ],
  content: [{ required: true, trigger: "blur", message: "请输简介" }],
});

const addrolerules = ref<FormRules<typeof addroleruleForm>>({
  role_name: [{ required: true, trigger: "blur", message: "请输入角色名" }],
  content: [{ required: true, trigger: "blur", message: "请输角色详情" }],
});

const addRoleBtn = () => {
  addroleruleForm.value = { role_name: "", img: "", content: "", mmg_id: 0 };
  addroledialogVisible.value = true;
};

// 选中角色
const checkedRole = (id: number) => {
  checkedRoleId.value = id;
  console.log(id);
};

// 删除角色
const delRole = async () => {
  if (checkedRoleId.value) {
    await reqDelRole({ id: checkedRoleId.value });
    ElMessage({
      message: "删除成功",
      type: "success",
    });
    getRole();
    checkedRoleId.value = 0;
  }
};

// 取消角色编辑
const cancelRoleEdit = () => {
  checkedRoleId.value = 0;
  isEdit.value = false;
};

// 打开角色图片
const openRolePicture = () => {
  getRolePicture();
  addrolePicturedialogVisible.value = true;
};

// 选中角色图片
const checkedRolePicture = (picture: any) => {
  checkedRolePictureInfo.value = picture;
};

// 取消选中角色图片
const cancelRolePicture = () => {
  checkedRolePictureInfo.value = { id: 0, img: "" };
  addrolePicturedialogVisible.value = false;
};

// 确定选中图片角色
const confirmRolePicture = () => {
  addroleruleForm.value.img = checkedRolePictureInfo.value.img;
  addrolePicturedialogVisible.value = false;
};

// 确定角色
const confirmRole = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async (valid) => {
    if (valid) {
      await reqAddRole(addroleruleForm.value);
      addroledialogVisible.value = false;
      getRole();
    } else {
      console.log("error submit!");
    }
  });
};

// 打开封面图
const openCover = () => {
  getPicture();
  coverdialogVisible.value = true;
};

// 选中图片
const checkedPicture = (picture: any) => {
  checkedCoverInfo.value = picture;
};

// 确定图片
const confirmCover = () => {
  addruleForm.value.cover = checkedCoverInfo.value.img;
  coverdialogVisible.value = false;
};

// 取消选择图片
const cancelCover = () => {
  checkedCoverInfo.value = { id: 0, img: "" };
  coverdialogVisible.value = false;
};

// 确定添加
const addsubmitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async (valid) => {
    if (valid) {
      addruleForm.value.play_time = addruleForm.value.play_time + "h";
      console.log("addruleForm.value", addruleForm.value);
      await reqGgmAdd(addruleForm.value);
      $router.replace("/playmanager/playlist");
    } else {
      console.log("error submit!");
    }
  });
};

// 分页
const changePage = (pageNum: number) => {
  page.value = pageNum;
  getPicture();
};

const changePageRole = (pageNum: number) => {
  pageRole.value = pageNum;
  getRolePicture();
};

// 图片上传成功后
const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  getPicture();
  getRolePicture();
};

// 图片上传前
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  // if (rawFile.type !== "image/jpeg") {
  //   ElMessage.error("Avatar picture must be JPG format!");
  //   return false;
  // } else
  if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("Avatar picture size can not exceed 2MB!");
    return false;
  }
  return true;
};

// 获取封面图片
const getPicture = async () => {
  let result = await reqGetPicture({
    type: coverType.value,
    page: page.value,
    pageSize: pageSize.value,
  });
  total.value = result.count;
  coverPictures.value = result.rows;
};

// 获取角色图片
const getRolePicture = async () => {
  let result = await reqGetPicture({
    type: roleType.value,
    page: pageRole.value,
    pageSize: pageSize.value,
  });
  totalRole.value = result.count;
  rolePictures.value = result.rows;
};

// 获取添加的角色
const getRole = async () => {
  let result = await reqGetRole(0);
  roleList.value = result.rows;
};

// 获取不同分类
const getCategoryList = async () => {
  let result = await reqCategoryList({ page: 1, pageSize: 100 });
  result.rows.forEach((item) => {
    if (item.type == 1) {
      circumstancesCateList.value.push(item);
    }
    if (item.type == 2) {
      peopleNumCateList.value.push(item);
    }
    if (item.type == 3) {
      characterCateList.value.push(item);
    }
  });
};

// 获取难度
const getDifficultyList = async () => {
  let result = await reqGetDifficulty();
  difficultyList.value = result;
};

onMounted(() => {
  getRole();
  getCategoryList();
  getDifficultyList();
});
</script>

<style scoped lang="scss">
.el-upload {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100px;
  height: 100px;
  border: 1px dotted rgb(202 194 194);
}

.bigbox {
  display: flex;
  flex-wrap: wrap;

  .box {
    position: relative;
    margin: 10px 15px;

    .del {
      position: absolute;
      top: -8px;
      right: -8px;
      display: flex;
      align-items: center;
      justify-content: center;
      width: 18px;
      height: 18px;
      cursor: pointer;
      background-color: black;
      border-radius: 50%;

      span {
        color: white;
      }
    }

    .overspread {
      position: absolute;
      inset: 0;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 30px;
      color: #fff;
      // top: 0;
      // bottom: 0;
      // left: 0;
      // right: 0;
      background: rgb(0 0 0 / 40%);
    }
  }
}

.btn {
  display: flex;
  justify-content: space-between;
  width: 100%;
}
</style>
